﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.IO.IsolatedStorage;
using BudgetManager.Utils;
using Microsoft.Phone.Tasks;
using BudgetManager.Resources;

namespace BudgetManager
{
    public partial class SettingsDetails : PhoneApplicationPage
    {
        public SettingsDetails()
        {
            InitializeComponent();
            loadValues();
        }
        
        #region EVENT HANDLERS

        ///// <summary>
        ///// Trigerred when LimitSettings toggle is turned off. Expenses will not be tracked on date
        ///// </summary>
        //private void limitUnchecked(object sender, RoutedEventArgs e)
        //{
            
        //}

        ///// <summary>
        ///// Trigerred when LimitSettings toggle is turned on Expenses will be tracked on date
        ///// </summary>
        //private void limitChecked(object sender, RoutedEventArgs e)
        //{
            

        //}

        /// <summary>
        /// Enent to modify the state of toggle witch
        /// </summary>
        private void toggleLimitSwitch(object sender, System.Windows.Input.GestureEventArgs e)
        {
            if (toggleLimit.IsChecked == true)
            {
                AppSettingsHelper.saveAppSettings("ToggleBalance", 1);
                if (!IsolatedStorageSettings.ApplicationSettings.Contains("BalanceLimit"))
                {
                    AppSettingsHelper.saveAppSettings("BalanceLimit", 0);
                    txtAmount.Text = "";
                }
                AppSettingsHelper.saveAppSettings("LimitSetDate", DateTime.Now.ToShortDateString());
                btnConfigure.Visibility = System.Windows.Visibility.Visible;
            }
            else
            {
                limitOnDateExpired.Visibility = System.Windows.Visibility.Collapsed;
                btnConfigure.Visibility = System.Windows.Visibility.Collapsed;
                cfgBalance.Visibility = System.Windows.Visibility.Collapsed;
                AppSettingsHelper.removeAppSettings("BalanceLimit");
                AppSettingsHelper.removeAppSettings("ToggleBalance");
                AppSettingsHelper.removeAppSettings("LimitSetDate");
            }
        }
        /// <summary>
        /// Saves the balnce configured by the user to be tracked for 30 days
        /// </summary>
        private void saveLimit(object sender, RoutedEventArgs e)
        {
            if (txtAmount.Text != "")
            {
                AppSettingsHelper.saveAppSettings("BalanceLimit", txtAmount.Text);
                AppSettingsHelper.saveAppSettings("LimitSetDate", DateTime.Now.ToShortDateString());
                cfgBalance.Visibility = System.Windows.Visibility.Collapsed;
                limitOnDateExpired.Visibility = System.Windows.Visibility.Collapsed;
            }
            else
            {
                MessageBox.Show(AppResources.ExpenseSaveSuccessfulMessage, AppResources.WarningMessageText, MessageBoxButton.OK);
            }
        }

        /// <summary>
        /// Opens a mail client with expense details as the mail content
        /// </summary>
        private void emailReport(object sender, System.Windows.Input.GestureEventArgs e)
        {
            //TODO: DELETE APPLICATION STORAGE FOR ALL BALANCE LIMIT ITEMS
            var limitSetDate = DateTime.Parse(IsolatedStorageSettings.ApplicationSettings["LimitSetDate"].ToString());
            EmailEntity entity = new EmailHelper().GetMailContentForExpenseReport(limitSetDate, limitSetDate.AddDays(30));
            EmailComposeTask emailComposeTask = new EmailComposeTask();

            emailComposeTask.Subject = entity.Subject;
            emailComposeTask.Body = entity.Body;
            emailComposeTask.Show();
        }

        /// <summary>
        /// Allows user to configure balance
        /// </summary>
        private void configureBalance(object sender, RoutedEventArgs e)
        {
            cfgBalance.Visibility = System.Windows.Visibility.Visible;
        }
        #endregion


        #region HELPER FUNCTIONS
        /// <summary>
        /// Loads the primary values
        /// </summary>
        private void loadValues()
        {
            if (IsolatedStorageSettings.ApplicationSettings.Contains("ToggleBalance"))
            {
                toggleLimit.IsChecked = true;
                var limitSetDate = DateTime.Parse(IsolatedStorageSettings.ApplicationSettings["LimitSetDate"].ToString());
                if (limitSetDate.AddDays(30) < DateTime.Now)
                {
                    //Settings period has expired. Prompt export and clear values
                    limitOnDateExpired.Visibility = System.Windows.Visibility.Visible;
                }
                else
                {
                    btnConfigure.Visibility = System.Windows.Visibility.Visible;
                    if (IsolatedStorageSettings.ApplicationSettings.Contains("BalanceLimit"))
                    {
                        txtAmount.Text = IsolatedStorageSettings.ApplicationSettings["BalanceLimit"].ToString();
                    }
                }
            }
        }



        #endregion

        #region OVERRIDED_FUNCTIONS
        /// <summary>
        /// Triggered when page is navigated from other pages
        /// </summary>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            string queryStr = string.Empty;
            NavigationContext.QueryString.TryGetValue("LandingPage", out queryStr);
            if (queryStr != string.Empty && queryStr != null)
            {
                settingsPage.DefaultItem = settingsPage.Items[int.Parse(queryStr)];
            }
            loadValues();
        }
        #endregion

        private void reviewClicked(object sender, RoutedEventArgs e)
        {
            MarketplaceReviewTask marketplaceReviewTask = new MarketplaceReviewTask();
            marketplaceReviewTask.Show();
        }


    }
}